<template>
  <el-dialog title="预览" v-model="dialogVisible" @close="handleDialogClose">
    <video ref="videoPlayer"
      style="max-width: 100%"
      v-if="dialogImageData.type == 'video'"
      :src="dialogImageUrl"
      controls
    />
    <div class="clearfix pos-rel" style="text-align: center" v-else>
      <template v-if="imageView && imageView.length > 0">
        <el-button
          plain
          :disabled="currentIndex == 0"
          class="fxl"
          @click="prevImage"
          >上一张
        </el-button>
        <el-button
          plain
          :disabled="currentIndex == imageView.length - 1"
          class="fxr"
          @click="nextImage"
          >下一张
        </el-button>
        <div class="clear h10"></div>
      </template>
      <img style="max-width: 100%" :src="dialogImageUrl" />
    </div>
  </el-dialog>
  <el-form
    style="width: 100%; height: 100%"
    ref="ruleForm"
    :model="formData"
    v-loading="formLoading"
    :rules="rules"
    label-width="220px"
  >
    <el-row>
      <el-col
        :span="item.fenl24"
        v-for="(item, index) in formDefine"
        :key="index"
      >
        <el-form-item
          :prop="
            item.biaodyz == 'required'
              ? item.zidmc
              : item.biaodyz != '' || (item.biaodyz != '') != null
              ? item.zidmc
              : ''
          "
          :label="
            item.biaodkjlx == '9' && topStepId != '1779359204496863233'
              ? ''
              : item.biaot
          "
        >
          <!--视频附件-->
          <div
            v-if="
              item.biaodkjlx == '9' &&
              showSecond == false &&
              topStepId == '1779359204496863233'
            "
          >
            <el-upload
              :on-preview="handlePictureCardPreview"
              :on-success="
                handleSuccess(formData[item.zidmc], 'video', item.zidmc)
              "
              :file-list="formData[item.zidmc]"
              ::headers="uploadHeaders"
              accept="video/*"
              :action="uploadAction"
            >
              <el-button type="primary">点击上传视频</el-button>
              <template #tip>
                <div class="el-upload__tip">
                  {{ item.kongjsj }}
                </div>
              </template>
            </el-upload>
            <div class="info clearfix">
              <P>一、视频时长要求2 分钟以内</P>
              <P>二、视频格式要求：</P>
              <P>1、作品视频画质清晰（清晰度在 720p 以上）</P>
              <P>2、以横屏 16：9 为佳，音质完好</P>
              <P>3、格式为 MP4、AVI、M4V、MOV等主流视频格式</P>
              <P>4、单个视频文件大小不超过 500M</P>
              <P>
                三、视频内容要求：参赛作品视频围绕主要设计亮点展开，画面必须使用作品的实景图或实景拍摄素材，可采取“作品图轮播+字幕+旁白解说”的剪辑形式，可自主选择添加背景音乐。为了投票公平原则，视频片头片尾可出现作品名称，但参赛者不能在视频中出镜，视频全片不能出现参赛设计师姓名或参赛设计单位的字样或旁白。</P
              >
            </div>
          </div>
          <div v-else>
            <video
              style="width: 100%"
              :src="formData[item.zidmc][0].url"
              v-if="
                item.biaodkjlx == '9' &&
                formData[item.zidmc] &&
                formData[item.zidmc].length > 0 &&
                formData[item.zidmc][0].url !== null
                  ? formData[item.zidmc][0].url
                  : ''
              "
              controls
            />
          </div>
          <!--上传附件-->
          <div class="clearfix" v-if="item.biaodkjlx == '6'">
            <el-upload
              :class="{ 'no-upload': disabled }"
              accept=".xls,.xlsx,.doc,.docx,.pdf,.rar,.zip,.jpg,.jpeg,.png,.gif,.bmp,.pdf,.JPG,.JPEG,.PBG,.GIF,.BMP,.PDF"
              :on-preview="handleDownLoadFile"
              :on-success="
                handleSuccess(formData[item.zidmc], 'file', item.zidmc)
              "
              :file-list="formData[item.zidmc]"
              ::headers="uploadHeaders"
              :action="uploadAction"
            >
              <el-button type="primary">点击上传文件</el-button>
              <template #tip>
                <div class="el-upload__tip">
                  {{ item.kongjsj }}
                </div>
              </template>
            </el-upload>
          </div>

          <!--上传图片-->
          <div class="clearfix" v-if="item.biaodkjlx == '5'">
            <div class="clearfix" v-if="!disabled">
              <el-upload
                :prop="item.zidmc"
                :class="{ 'no-upload': disabled }"
                :on-preview="handlePictureCardPreview"
                :before-upload="beforeUpload"
                :on-success="
                  handleSuccess(formData[item.zidmc], 'photo', item.zidmc)
                "
                multiple
                accept=".jpg,.jpeg,.png,.gif,.bmp,.JPG,.JPEG,.PBG,.GIF,.BMP"
                :file-list="formData[item.zidmc]"
                :headers="uploadHeaders"
                :action="uploadAction"
                list-type="picture-card"
              >
                <i class="el-icon" style="font-size: 20px">
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    viewBox="0 0 1024 1024"
                    data-v-ea893728=""
                  >
                    <path
                      fill="currentColor"
                      d="M480 480V128a32 32 0 0 1 64 0v352h352a32 32 0 1 1 0 64H544v352a32 32 0 1 1-64 0V544H128a32 32 0 0 1 0-64z"
                    ></path>
                  </svg>
                </i>
              </el-upload>
              <div class="clear"></div>
              <div class="clearfix font-gray">上传的图片大小不能超过5M</div>
            </div>
            <div class="clearfix" v-else>
              <viewer
                class="viewer small"
                ref="viewer"
                :images="formData[item.zidmc]"
              >
                <img
                  class="pointer"
                  v-for="(img, index) in formData[item.zidmc]"
                  :src="img.url"
                  :key="index"
                />
              </viewer>
            </div>
          </div>
          <!--          :on-remove="handleRemove(formData[item.zidmc])"-->
          <el-radio-group
            :disabled="disabled"
            v-if="item.biaodkjlx == '8'"
            v-model="formData[item.zidmc]"
            @change="radioChange"
          >
            <el-radio
              :label="item2.split(',')[1]"
              v-for="item2 in item.kongjsj.split(';')"
            >
              {{ item2.split(",")[0] }}
            </el-radio>
          </el-radio-group>
          <el-input
            :class="{ 'blank-font': disabled }"
            :prop="item.zidmc"
            :disabled="disabled"
            :placeholder="`请输入${item.biaot}`"
            v-if="item.biaodkjlx == '1'"
            v-model="formData[item.zidmc]"
          ></el-input>
          <template  v-if="item.biaodkjlx == '4'">
            <el-input v-if="!disabled"
                :disabled="disabled"
                :placeholder="`请输入${item.biaot}`"
                type="textarea"
                :rows="5"
                v-model="formData[item.zidmc]"
            ></el-input>
            <div v-else class="dis-list">{{formData[item.zidmc]}}</div>
          </template>


          <el-select
            :disabled="disabled"
            :placeholder="`请选择${item.biaot}`"
            v-if="item.biaodkjlx == '2'"
            v-model="formData[item.zidmc]"
          >
            <el-option
              v-for="item2 in item.kongjsj.split(';')"
              :label="item2.split(',')[0]"
              :value="item2.split(',')[1]"
            >
            </el-option>
          </el-select>

          <!--级联-->
          <el-cascader
            :class="formData[item.zidmc] != '' ? 'no-rules' : ''"
            :placeholder="`请选择${item.biaot}`"
            :disabled="disabled"
            v-if="item.biaodkjlx == '3'"
            :props="props"
            v-model="formData[item.zidmc]"
            :options="options[item.zidmc]"
          ></el-cascader>

          <div class="pos-rel" style="width: 100%">
            <div class="pos-abs disabled-top" v-if="disabled"></div>
            <circular-fields
              :table-data="tableData"
              :disabled="disabled"
              v-if="item.biaodkjlx == '10'"
              :fields-data="tableFormHeader[item.zidmc]"
            ></circular-fields>
          </div>
          <div :class="{ 'no-upload': disabled }">
            <el-button
              :loading="btnLoading"
              @click="clickPdf(item)"
              v-if="item.biaodkjlx == '11'"
              type="primary"
              >导出
            </el-button>
          </div>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<script>
import axios from "axios";
import circularFields from "./circularFields.vue";
import formDataPdf from "@/view/pc/components/fomDataPdf.vue";

export default {
  name: "fomData",
  inject: ["imageUrl", "serviceUrl"],
  components: {
    formDataPdf,
    circularFields,
  },
  props: {
    params: Object,
  },
  data() {
    return {
      formLoading: false,
      pdfStatic: false,
      fieldsData: [
        { name: "项目名称", value: "name", type: "input" },
        { name: "项目类型", value: "type", type: "input", width: 140 },
        { name: "项目面积", value: "area", type: "input", width: 100 },
        { name: "项目所在地", value: "local", type: "input" },
        {
          name: "是否已选材",
          value: "materials",
          type: "radio",
          data: [
            { name: "是", value: 0 },
            { name: "否", value: 1 },
          ],
          width: 140,
        },
        { name: "项目用灯需求", value: "requirements", type: "textarea" },
        { name: "操作", value: "oper", width: 100 },
      ],
      props: {
        expandTrigger: "click",
        value: "key",
        label: "title",
      },
      tableFormHeader: {},
      tableData: [{}],
      tableFormData: {},
      rules: {},
      rulesNo: {},
      options: {},
      showSecond: false,
      dialogImageUrl: null,
      dialogImageData: {},
      dialogVisible: false,
      dangqsf: 1,
      disabled: false,
      formDisabled: 2, //2 false  1 true
      menuName: "",
      uploadAction: this.serviceUrl + "/sys/common/upload",
      uploadHeaders: {
        "X-Access-Token": localStorage.getItem("token"),
      },
      fileList: [],
      formData: {
        // pdf:[]
      },

      formDefine: [],
      allFormDefine: [],
      daqsc: null,
      saisId: null,
      pdfData: [],
      currentMenu: "",
      hasRules: true,
      formType: "",
      topStepId: "",
      currentImage: "",
      currentIndex: 1,
      imageView: [],
      userData: {},
      btnLoading: false,
      canssfValue: "1",
    };
  },

  computed: {},
  mounted() {
    this.formType = localStorage.getItem("formType");
    this.topStepId = localStorage.getItem("topStepId");
    this.formDisabled = localStorage.getItem("formDisabled");
    this.disabled = this.formDisabled == 2 ? false : true;
  },

  methods: {
    handleDialogClose(){
      const videoPlayer = this.$refs.videoPlayer;
      if (videoPlayer) {
        videoPlayer.pause();
        // 重置视频播放位置，如果需要的话
        videoPlayer.currentTime = 0;
      }
    },
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 5; // 小于2MB
      if (!isLt2M) {
        this.$message.warning("上传的图片大小不能超过 5MB!");
      }
      return isLt2M;
    },
    clickPdf() {
      this.$emit("getPdf", "item");
    },
    handleDownLoadFile(uploadFile) {
      location.href = uploadFile.url;
    },

    handleSuccess($fileList, type, fields) {
      console.log($fileList,'$fileList');
      let that = this;
      // console.log($fileList, type, fields,'$fileList, type, fields');
      return function (response, file, fileList) {
        // console.log(response, file, fileList,'response, file, fileList');
        // $fileList.splice(0, $fileList.length);
        // fileList.forEach((item) => {
        //   $fileList.push({
        //     uid: item.uid,
        //     name: item.name,
        //     type: type,
        //     fields: fields,
        //     // url: item.response ? that.imageUrl + item.response.message : item.url
        //     url: item.response?item.response.message:item.url,
        //   });
        // });

        if (response.message) {
          $fileList.push({
            uid: file.uid,
            name: file.name,
            type: type,
            fields: fields,
            url: response.message,
          });
        }

        console.log(fileList);
      };
    },

    getFormDefine(params, menu, num) {
      this.formLoading = true;
      this.menuName = menu;
      console.log(this.menuName, "this.menuName");
      axios
        .get(this.serviceUrl + "/saisjczd2/cbda2Saisjczd/getFormDefine", {
          headers: {
            "X-Access-Token": localStorage.getItem("token"),
          },
          params: {
            ...params,
            _t: new Date().getTime(),
          },
        })
        .then((resp) => {
          if (resp && resp.data.code == 200) {
            this.formLoading = false;
            if (this.formType == "radio") {
              this.allFormDefine = resp.data.result;
              switch (menu) {
                case "project2":
                  this.disabled = false;
                  this.radioChange(this.canssfValue ? this.canssfValue : "1");
                  break;
                case "zuopxq":
                  this.radioChange(this.canssfValue);
                  this.showSecond = false;
                  break;
                case "pings":
                  this.radioChange(this.canssfValue);
                  if (num && num == 0) {
                    this.disabled = false;
                  } else {
                    this.disabled = true;
                  }
                  this.showSecond = true;
                  break;
              }
            } else {
              this.formDefine = resp.data.result;
              this.JudgingForms();
            }
          }
        })
        .catch((error) => {
          //console.log(error);
        });
      console.log(this.formDefine, "formData");
    },

    // 表单数据
    getFormData(params, menu, num) {
      axios
        .get(this.serviceUrl + "/saisjczd2/cbda2Saisjczd/getFormData", {
          headers: {
            "X-Access-Token": localStorage.getItem("token"),
          },
          params: {
            ...params,
            _t: new Date().getTime(),
          },
        })
        .then((resp) => {
          if (resp.data.success) {
            //所有视频图片 回显时变成数组
            let params = resp.data.result;
            this.canssfValue = params.canssf ? params.canssf : "1";
            for (let key in params) {
              if (params[key] !== null && params[key] !== "") {
                if (
                  JSON.stringify(params[key]).includes("[") &&
                  JSON.stringify(params[key]).includes("]")
                ) {
                  if (key !== "dangqzjxm") {
                    params[key] = JSON.parse(params[key]);
                  } else {
                    params[key] = JSON.parse(params[key].replace(/\n/g, ''));
                    // params[key] = JSON.parse(
                        // params[key].replace(/\n/g, '\r\n')
                      // params[key].replace(/\n/g, "\\n").replace(/\r/g, "\\r")
                    // );
                  }
                }
              }
            }
            console.log(params, "params.dangqzjxm********");
            this.tableData = params.dangqzjxm;
            this.formData = params;
            this.$forceUpdate();
          } else this.$message.error(resp.data.message);
        })
        .catch((error) => {
          //console.log(error);
        });
    },
    // 表单判断
    JudgingForms(e) {
      this.rules = {};
      let param = {};
      this.formDefine.forEach((item) => {
        //级联数据
        if (
          item.biaodkjlx == "3" &&
          (this.menuName == "project2" ||
            this.menuName == "zuopxq" ||
            this.menuName == "pings")
        ) {
          this.options[item.zidmc] = [];
          this.getOptionsDataForm(item.zidbm, item.zidmc);
        }
        //子表格表头
        if (
          item.biaodkjlx == "10" &&
          (this.menuName == "project2" || this.menuName == "zuopxq")
        ) {
          this.tableFormHeader[item.zidmc] = eval("(" + item.kongjsj + ")");
        }
        if (item.biaodkjlx == "10" && this.menuName == "pings") {
          let data = eval("(" + item.kongjsj + ")");
          this.tableFormHeader[item.zidmc] = data.splice(0, data.length - 1);
        }
        if (this.menuName == "project2" || this.menuName == "zuopxq") {
          //初始化formData
          this.formData[item.zidmc] =
            item.biaodkjlx == "9" ||
            item.biaodkjlx == "6" ||
            item.biaodkjlx == "5" ||
            item.biaodkjlx == "10"
              ? this.formData[item.zidmc] &&
                this.formData[item.zidmc].length > 0
                ? this.formData[item.zidmc]
                : []
              : this.formData[item.zidmc] && this.formData[item.zidmc] != ""
              ? this.formData[item.zidmc]
              : "";
          if (this.menuName == "project2") {
            if (this.userData) {
              this.formData[item.zidmc] =
                  item.biaodkjlx == "9" ||
                  item.biaodkjlx == "6" ||
                  item.biaodkjlx == "5" ||
                  item.biaodkjlx == "10"
                      ? this.userData[item.zidmc] &&
                      this.userData[item.zidmc].length > 0
                          ? this.userData[item.zidmc]
                          : []
                      : this.userData[item.zidmc] && this.userData[item.zidmc] != ""
                          ? this.userData[item.zidmc]
                          : "";
              this.canssfValue = e?e:this.userData.canssf;
            }
          }

          //初始化rule 正则
          if (item.biaodyz == "required") {
            this.rules[item.zidmc] = {
              required: true,
              message: `"${item.biaot}"不能为空`,
              trigger: "blur",
            };
          } else if (
            item.biaodyz != "" &&
            item.biaodyz != null &&
            item.biaodyz != "required"
          ) {
            param[item.zidmc] = item.biaodyz;
            this.rules[item.zidmc] = [
              {
                required: true,
                message: `"${item.biaot}"不能为空`,
                trigger: "blur",
              },
              {
                pattern:
                  item.zidmc === "lianxdh" || item.zidmc === "duijrdh"
                    ? /^1[3-9]\d{9}$/
                    : item.zidmc === "youx"
                    ? /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/
                    : item.zidmc === "zhengjhm"
                    ? /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
                    : "",
                message: `"${item.biaot}"格式不对`,
                trigger: "blur",
              },
            ];
          }
        }
      });
      console.log(this.formData,'this.formData*******-----*******');
    },

    radioChange(e) {
      this.$refs.ruleForm.resetFields();
      this.dangqsf = e;
      if (e == 1) {
        this.formDefine = this.allFormDefine.filter(
          (item) => item.cansrsf != 2
        );
      } else if (e == 2) {
        this.formDefine = this.allFormDefine.filter(
          (item) => item.cansrsf != 1
        );
      }
      this.JudgingForms(e);
      this.canssfValue = e;
      this.formData.canssf = e;
    },
    // 级联控件数据
    getOptionsDataForm(zidbm, name) {
      axios
        .get(this.serviceUrl + "/sys/category/loadTreeRoot", {
          headers: {
            "X-Access-Token": localStorage.getItem("token"),
          },
          params: {
            async: false,
            pcode: zidbm,
            _t: new Date().getTime(),
          },
        })
        .then((resp) => {
          this.options[name] = resp.data.result;
        })
        .catch((error) => {
          //console.log(error);
        });
    },

    handleRemove($fileList) {
      console.log($fileList);
      return function (response, file, fileList) {
        fileList.forEach((item) => {
          $fileList.push({
            uid: item.uid,
            name: item.name,
            // url: item.response ? this.imageUrl + item.response.message : item.url
            url: item.response.message,
          });
        });
      };
    },
    handlePictureCardPreview(file) {
      this.dialogImageData = file;
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
      this.imageView = this.formData[file.fields];
      this.imageView &&
        this.imageView.forEach((item, index) => {
          if (item.url === file.url) {
            this.currentIndex = index;
          }
        });
    },
    // 实现上一张下一张功能
    prevImage() {
      if (this.currentIndex > 0) {
        this.currentIndex -= 1;
        this.dialogImageUrl = this.imageView[this.currentIndex].url;
      }
    },
    nextImage() {
      if (this.currentIndex < this.imageView.length - 1) {
        this.currentIndex += 1;
        this.dialogImageUrl = this.imageView[this.currentIndex].url;
      }
      console.log(this.currentIndex);
    },
  },
  // watch: {
  //   formDefine: {
  //     handler: function (newItems, oldItems) {
  //       console.log('新数组:', newItems);
  //       console.log('旧数组:', oldItems);
  //     },
  //     deep: true
  //   }
  // }
};
</script>

<style scoped lang="less">
:deep(.el-cascader) {
  width: 100%;
}

:deep(.el-upload-list) {
  min-width: 500px;
  font-size: 16px;
}

:deep(.el-upload-list__item-file-name) {
  overflow: hidden;
  text-overflow: inherit;
  white-space: normal;
}

.no-upload {
  :deep(.el-upload--picture-card),
  :deep(.el-button),
  :deep(.el-form-item),
  :deep(.el-upload-list__item-delete) {
    display: none !important;
  }
}

.info {
  p {
    font-size: 12px;
    color: #999;
    line-height: 18px;
  }
}

.el-upload-list__item .el-icon--close-tip {
  display: none;
}

.viewer {
  img {
    height: 100px;
    margin: 10px;
    padding: 5px;
    border: 1px dashed #ddd;
  }
}
.font-gray {
  color: #999;
}
.dis-list{
  background:#f6f7fa;
  border-radius:5px;
  padding:8px;
  line-height: 20px;
  border:1px solid #e4e7ed;
  min-height:10px;
  width:100%;
}
</style>
